# -*- coding:utf-8 -*-
import sys
import winreg
from datetime import datetime
import shutil
import os
import ctypes
import os.path
import threading
import concurrent.futures
import random
import requests
import json
import datetime
from tqdm.rich import tqdm
import warnings
import colorama
import tkinter as tk
from tkinter import filedialog
from concurrent.futures import ThreadPoolExecutor

#屏蔽证书警告
requests.packages.urllib3.disable_warnings()
warnings.simplefilter("ignore")

#All functions by Hypixice

"""
Popularity() -人气 -返回值 str
get_welcome_message() -获取欢迎语 str
copy_and_replace(source_folder, destination_folder) -复制并替换（文件夹） execute

AES_key(key) -设置一个key
- Hypixice_sign_encrypt(text) -加密内容 str
- Hypixice_sign_decrypt(text) -解密内容 str

delete(path) -删除某个文件夹（多线程） execute
clear_terminal() -清屏 execute
get_ret() -获取当前程序目录 str
is_admin() -是否是以管理权限运行？ True/False
get_reg (path,name) -获取某个注册表键值 str
WGETH_D_N(RUL, Path) -下载一个huang1111云盘的文件(NoGUI) execute
WGETH_D(RUL, Path) -下载一个huang1111云盘的文件 execute
WGET_D(RUL, Path, Name) -下载一个文件 execute
"""




def Personal():
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
    path = winreg.QueryValueEx(key, "Personal")[0]
    return path

def Popularity():
    today = datetime.date.today()
    today_time = f"{today.year}-{today.month}-{today.day}"
    if os.path.exists(f"{Personal()}\\popularity"):
        if os.path.exists(f"{Personal()}\\popularity\\popularity.json"):
            with open(file=f"{Personal()}\\popularity\\popularity.json",mode="r",encoding="utf-8") as f:
                examine_date = f.read()
                examine_date1 = json.loads(examine_date)
                examine_date2 = examine_date1['time']
                if examine_date2 != today_time:
                    with open(file=f"{Personal()}\\popularity\\popularity.json", mode="w", encoding="utf-8") as f:
                        data = {
                            "data": f"{random.randint(1, 100)}",
                            "time": f"{today_time}"
                        }
                        f.write(json.dumps(data, indent=4, ensure_ascii=False))
                        f.close()

                    with open(file=f"{Personal()}\\popularity\\popularity.json", mode="r", encoding="utf-8") as f:
                        points = f.read()
                        points1 = json.loads(points)
                        points2 = int(points1['data'])
                        if points2 <= 20:
                            return f"今天的人品评分是 {points2}，非常糟糕，请小心行事！"
                        elif points2 <= 40:
                            return f"今天的人品评分是 {points2}，你的运气比较差，要多加小心！"
                        elif points2 <= 60:
                            return f"今天的人品评分是 {points2}，还算平均，不过要抓住机会哦！"
                        elif points2 <= 80:
                            return f"今天的人品评分是 {points2}，运气不错，有机会会有好事发生！"
                        else:
                            return f"今天的人品评分是 {points2}，非常好，好运连连！"
                if examine_date2 == today_time:
                    with open(file=f"{Personal()}\\popularity\\popularity.json", mode="r", encoding="utf-8") as f:
                        points = f.read()
                        points1 = json.loads(points)
                        points2 = int(points1['data'])
                        if points2 <= 20:
                            return f"今天的人品评分是 {points2}，非常糟糕，请小心行事！"
                        elif points2 <= 40:
                            return f"今天的人品评分是 {points2}，你的运气比较差，要多加小心！"
                        elif points2 <= 60:
                            return f"今天的人品评分是 {points2}，还算平均，不过要抓住机会哦！"
                        elif points2 <= 80:
                            return f"今天的人品评分是 {points2}，运气不错，有机会会有好事发生！"
                        else:
                            return f"今天的人品评分是 {points2}，非常好，好运连连！"
        else:
            with open(file=f"{Personal()}\\popularity\\popularity.json", mode="w", encoding="utf-8") as f:
                data = {
                    "data": f"{random.randint(1, 100)}",
                    "time": f"{today_time}"
                }
                f.write(json.dumps(data, indent=4, ensure_ascii=False))
                f.close()
            with open(file=f"{Personal()}\\popularity\\popularity.json", mode="r", encoding="utf-8") as f:
                points = f.read()
                points1 = json.loads(points)
                points2 = int(points1['data'])
                if points2 <= 20:
                    return f"今天的人品评分是 {points2}，非常糟糕，请小心行事！"
                elif points2 <= 40:
                    return f"今天的人品评分是 {points2}，你的运气比较差，要多加小心！"
                elif points2 <= 60:
                    return f"今天的人品评分是 {points2}，还算平均，不过要抓住机会哦！"
                elif points2 <= 80:
                    return f"今天的人品评分是 {points2}，运气不错，有机会会有好事发生！"
                else:
                    return f"今天的人品评分是 {points2}，非常好，好运连连！"

    else:
        os.makedirs(f"{Personal()}\\popularity")
        with open(file=f"{Personal()}\\popularity\\popularity.json", mode="w", encoding="utf-8") as f:
            data = {
                "data": f"{random.randint(1, 100)}",
                "time": f"{today_time}"
            }
            f.write(json.dumps(data, indent=4, ensure_ascii=False))
            f.close()
        with open(file=f"{Personal()}\\popularity\\popularity.json", mode="r", encoding="utf-8") as f:
            points = f.read()
            points1 = json.loads(points)
            points2 = int(points1['data'])
            if points2 <= 20:
                return f"今天的人品评分是 {points2}，非常糟糕，请小心行事！"
            elif points2 <= 40:
                return f"今天的人品评分是 {points2}，你的运气比较差，要多加小心！"
            elif points2 <= 60:
                return f"今天的人品评分是 {points2}，还算平均，不过要抓住机会哦！"
            elif points2 <= 80:
                return f"今天的人品评分是 {points2}，运气不错，有机会会有好事发生！"
            else:
                return f"今天的人品评分是 {points2}，非常好，好运连连！"
            
class colors:
    HEADER = colorama.Fore.RESET
    BLUE = colorama.Fore.LIGHTCYAN_EX
    GREEN = colorama.Fore.LIGHTGREEN_EX
    WARNING = colorama.Fore.LIGHTYELLOW_EX
    FAIL = colorama.Fore.LIGHTRED_EX
    ENDC = colorama.Fore.RESET
    UNDERLINE = colorama.Fore.RESET
    RESET = colorama.Fore.RESET
    INOF = colorama.Fore.LIGHTWHITE_EX
    
#welcome message
def get_welcome_message():
    current_hour = datetime.datetime.now().hour

    if current_hour < 6:
        return "夜深了，早点睡觉吧~"
    elif current_hour < 12:
        return "早上好！祝您有个美好的一天~"
    elif current_hour < 18:
        return "下午好！愿您度过愉快的时光~"
    else:
        return "晚上好！祝您度过愉快的夜晚~"
    
    

    
def copy_and_replace(source_folder, destination_folder):
    if not os.path.exists(destination_folder):
        os.makedirs(destination_folder)

    def copy_files(src, dst):
        for item in os.listdir(src):
            s = os.path.join(src, item)
            d = os.path.join(dst, item)
            if os.path.isdir(s):
                if not os.path.exists(d):
                    os.makedirs(d)
                with concurrent.futures.ThreadPoolExecutor() as executor:
                    executor.submit(copy_files, s, d)  # 在创建新的线程池中执行复制文件操作
            else:
                shutil.copy2(s, d)

    with concurrent.futures.ThreadPoolExecutor() as executor:
        executor.submit(copy_files, source_folder, destination_folder)

    executor.shutdown()  # 清理资源

def op(out,put):
    now = datetime.datetime.now()
    current_time = now.strftime("%H:%M:%S")
    if put == "1":
        print(f"[Information：{current_time}] {out}" + colors.ENDC)
    elif put == "2":
        print(colors.GREEN + f"[Success：{current_time}] " + colors.ENDC + str(out))
    elif put == "3":
        print(colors.FAIL + f"[Error：{current_time}] " + colors.ENDC + str(out))
    elif put == "4":
        print(colors.WARNING + f"[WARNING：{current_time}] " + colors.ENDC + str(out))
        
        
def op_s(text):
    return text.replace("\\n", "\n")

def op_s_1(text):
    return text.replace("%N%", "\n")
            

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

def download(url, save_path, file_name):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0'
    }
    response = requests.get(url, headers=headers, verify=False, stream=True)
    
    if 'Content-Length' in response.headers:
        file_size = int(response.headers['Content-Length']) / 1024  
    else:
        op("Content-Length header is not available. Unable to display progress.","4")
        file_size = None

    full_file_path = f"{save_path}\\\\{file_name}"

    with open(full_file_path, mode="wb") as f:
        if file_size:
            with ThreadPoolExecutor(max_workers=12) as executor:
                for data in tqdm(executor.map(lambda x: x, response.iter_content(1024)), total=file_size, unit='k', desc=f"Downloading...[{file_name}]"):
                    f.write(data)
        else:
            for data in response.iter_content(1024):
                f.write(data)

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0'
}


#Wget(NoGUI)
def WGETH_D_N(RUL, Path,name):
    pathx_pyinstaller = Path
    op("正在获取直连下载地址...","1")
    get_download_client = RUL
    get_download_client_download = json.loads(requests.put(f"https://pan.huang1111.cn/api/v3/share/download/{get_download_client.split('/')[-1]}",headers=headers,verify=False).text)
    op("获取成功","2")
    get_download_client_file_name = json.loads(requests.get(f"https://pan.huang1111.cn/api/v3/share/info/{get_download_client.split('/')[-1]}",headers=headers,verify=False).text)
   # print(get_download_client_file_name," | ",f" {get_download_client_file_name['data']['source']['name']}", "|", {get_download_client_download['data']})
    if os.path.isfile(f"{pathx_pyinstaller}\\{get_download_client_file_name['data']['source']['name']}"):
        op("删除上次残留文件...","1")
        os.remove(f"{pathx_pyinstaller}\\{get_download_client_file_name['data']['source']['name']}")
    op("正在下载文件...","1")
    global get_name
    get_name = f"{get_download_client_file_name['data']['source']['name']}"
    download(f"{get_download_client_download['data']}",f"{pathx_pyinstaller}",f"{name}")

#Wget
def WGETH_D(RUL):
    op("请选择保存目录","1")
    root = tk.Tk()
    root.withdraw()
    pathx_pyinstaller = filedialog.askdirectory(title='选择保存文件夹')

    op("正在获取直连下载地址...","1")
    get_download_client = RUL
    get_download_client_download = json.loads(requests.put(f"https://pan.huang1111.cn/api/v3/share/download/{get_download_client.split('/')[-1]}",headers=headers,verify=False).text)
    op("获取成功","2")
    get_download_client_file_name = json.loads(requests.get(f"https://pan.huang1111.cn/api/v3/share/info/{get_download_client.split('/')[-1]}",headers=headers,verify=False).text)
   # print(get_download_client_file_name," | ",f" {get_download_client_file_name['data']['source']['name']}", "|", {get_download_client_download['data']})
    if os.path.isfile(f"{pathx_pyinstaller}\\{get_download_client_file_name['data']['source']['name']}"):
        op("删除上次残留文件...","1")
        os.remove(f"{pathx_pyinstaller}\\{get_download_client_file_name['data']['source']['name']}")
    op("正在下载文件...","1")
    download(f"{get_download_client_download['data']}",f"{pathx_pyinstaller}",f"{get_download_client_file_name['data']['source']['name']}")
    op(f"下载完成,压缩文件保存位置:{pathx_pyinstaller}\\{get_download_client_file_name['data']['source']['name']}","2")



#Wget(Not Huang111)(NoGUI)
def WGET_D_N(RUL, Path, Filename):
    pathx_pyinstaller = Path
    op("正在获取直连下载地址...","1")
    op("获取成功","2")
    if os.path.isfile(f"{pathx_pyinstaller}\\{Filename}"):
        op("删除上次残留文件...","1")
        os.remove(f"{pathx_pyinstaller}\\{Filename}")
    op("正在下载文件...","1")
    download(f"{RUL}",f"{pathx_pyinstaller}",f"{Filename}")

    

def delete_directory(path):
    shutil.rmtree(path)

def delete(path_to_delete):
    delete_thread = threading.Thread(target=delete_directory, args=(path_to_delete,))
    delete_thread.start()
    delete_thread.join()


def delete_folder_content(folder_path):
    for file_name in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file_name)
        if os.path.isfile(file_path):
            os.remove(file_path)
        elif os.path.isdir(file_path):
            with concurrent.futures.ThreadPoolExecutor() as executor:
                executor.submit(delete_folder_content, file_path)
            os.rmdir(file_path)
            
            
def clear_terminal():
#    os.system('clear')  # for macOS and Linux
    os.system('cls')
    
def get_ret():
    ret = os.path.dirname(os.path.realpath(sys.argv[0]))
    return ret

def get_reg(path,name):
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, f"{path}")
    text = winreg.QueryValueEx(key, name)[0]
    return text